<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10 paddingBottom20">
        <el-form
          :inline="true"
          :rules="rules"
          :model="monitorForm"
          class="demo-form-inline"
          ref="userListFrom"
          label-width="90px"
        >
          <div class="main_crumbs boxdq">
            <div class="main_crumbs_l">
              <a href="javascript:;" @click="$router.back(-1)">
                <i class="el-icon-arrow-down"></i>返回
              </a>
              <em>|</em>
              <span>快捷设置</span>
            </div>
          </div>
          <div class="">
            <!-- 搜索 -->
            <div class="batch-wrap">
              <div class="mainor_form">
                <el-form-item
                  label="商品分类："
                  prop="form.category_id"
                  class="wid220"
                >
                  <el-cascader
                    v-model="monitorForm.form.category_id"
                    :options="options"
                    :props="defaultProps"
                  ></el-cascader>
                </el-form-item>
                <el-form-item label="标品：" prop="form.is_standard">
                  <el-select
                    v-model.trim="monitorForm.form.is_standard"
                    placeholder="是否标品"
                    class="wid220"
                  >
                    <el-option label="所有" value=""></el-option>
                    <el-option
                      v-for="(is_standard_list, index) in info.is_standard_list"
                      :key="index"
                      :label="is_standard_list"
                      :value="parseInt(index + 1)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="商品：" prop="form.name">
                  <change-goods-input
                    isInventory
                    ref="changeGoodsInput"
                    @clear="
                      () => {
                        this.monitorForm.form.name = '';
                      }
                    "
                    @sendValue="
                      (data) => {
                        this.monitorForm.form.name = data.id;
                      }
                    "
                  ></change-goods-input>
                </el-form-item>
                <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="false">
                </MainFormBtn>
              </div>
            </div>
            <!-- 表格 -->
            <div class="main_table marginTop10" style="min-height: 550px">
              <el-table
                ref="multipleTable"
                v-loading="listLoading"
                :data="monitorForm.list.data"
                element-loading-text="加载中"
                fit
                border
                key="multipleTable"
                highlight-current-row
              >
                <el-table-column label="商品名称" width="180" prop="name">
                  <template slot-scope="scope"
                    >{{ scope.row.goods.name }}【{{
                      scope.row.spu_name ? scope.row.spu_name.title : ""
                    }}】</template
                  >
                </el-table-column>
                <el-table-column label="单位" prop="spu_unit.title" />
                <el-table-column
                  label="期初库存"
                  width="180"
                  prop="num"
                  class-name="main_hei"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'list.data.' + scope.$index + '.num'"
                      :rules="rules.num"
                      label-width="10px"
                      label=" "
                    >
                      <el-input
                        :ref="'list.data.' + scope.$index + '.num'"
                        v-model.trim="scope.row.num"
                        placeholder="期初库存"
                        :class="[
                          'wid110',
                          'list_data_' + scope.$index + '_num',
                        ]"
                        @focus="inputFocus(scope, $event, 1)"
                        @blur="inputBlur(scope, $event, 1)"
                        @keyup.enter="nextFocus(scope, $event, 1)"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="期初进价"
                  width="180"
                  prop="price"
                  class-name="main_hei"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'list.data.' + scope.$index + '.price'"
                      :rules="rules.price"
                      label-width="10px"
                      label=" "
                    >
                      <el-input
                        :ref="'list.data.' + scope.$index + '.price'"
                        v-model.trim="scope.row.price"
                        placeholder="期初进价"
                        class="wid110"
                        @focus="inputFocus(scope, $event, 2)"
                        @blur="inputBlur(scope, $event, 2)"
                        @keyup.enter.native="nextFocus(scope, $event, 2)"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="期初金额" class-name="main_hei">
                  <template slot-scope="scope">{{
                    parseFloat(scope.row.num) * parseFloat(scope.row.price)
                      ? $toFixed(
                          parseFloat(scope.row.num) *
                            parseFloat(scope.row.price)
                        )
                      : 0
                  }}</template>
                </el-table-column>
                <el-table-column
                  label="管理操作"
                  align="center"
                  fixed="right"
                  width="140"
                  class-name="main_hei"
                >
                  <template slot-scope="scope">
                    <el-link
                      type="success"
                      @click="confirm(scope.$index, scope.row)"
                      >确认</el-link
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 分页 -->
            <div class="main_page boxdq">
              <div></div>
              <!-- 分页 -->
              <div class="main_page_r">
                <MainPagination
                  :current-page="current.page"
                  :page-sizes="[20, 30, 50, 100]"
                  :page-size="limit"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalCount"
                  background
                  @size-change="changeLimit"
                  @current-change="changePage"
                />
              </div>
            </div>
          </div>
          <div class="main_tile boxdq marginTop20">
            <div class="main_tile_l marginLeft0"><em></em>商品信息</div>
          </div>
          <div class="main_table main_table_xs marginTop10">
            <el-table
              ref="multipleTable"
              v-loading="listLoading"
              :data="monitorForm.list_xs"
              element-loading-text="加载中"
              fit
              highlight-current-row
              key="multipleTable1"
            >
              <el-table-column label="序号">
                <template slot-scope="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column
                label="商品名称"
                prop="operate.name"
                class-name="main_hei"
              >
                <template slot-scope="scope"
                  >{{ scope.row.goods.name }}【{{
                    scope.row.spu_name ? scope.row.spu_name.title : ""
                  }}】</template
                >
              </el-table-column>
              <el-table-column
                label="单位"
                prop="spu_unit.title"
                class-name="main_hei"
              />
              <el-table-column
                label="期初库存"
                prop="num"
                class-name="main_hei"
              />
              <el-table-column
                label="期初进价"
                prop="price"
                class-name="main_hei"
              />
              <el-table-column label="期初金额" class-name="main_hei">
                <template slot-scope="scope">{{
                  parseFloat(scope.row.num) * parseFloat(scope.row.price)
                    ? $toFixed(
                        parseFloat(scope.row.num) * parseFloat(scope.row.price)
                      )
                    : 0
                }}</template>
              </el-table-column>
              <el-table-column
                label="管理操作"
                align="center"
                fixed="right"
                width="240"
                class-name="main_hei"
              >
                <template slot-scope="scope">
                  <el-link type="danger" @click="delet(scope.$index)"
                    >删除</el-link
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
        <div class="newConBox_p200 paddingBottom10" id="newConBox">
          <div class="newConBox_h32">
            <div
              :class="['mainor_pr boxdq newConBox ', { on: searchBarFixed }]"
            >
              <div class="mainor_prl">
                <el-button type="primary" @click="preservation" v-repeatClick
                  >保存</el-button
                >
                <el-button @click="$router.back(-1), (isEdit = false)"
                  >取消</el-button
                >
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  opening_getUnOpening,
  storage_add,
} from "@/api/warehouse/warehouseStock";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import rules from "@/rules/warehouse/warehouseStock_quick";
import { recursion, category } from "@/utils/index";

export default {
  components: {},
  data() {
    return {
      // 验证
      rules,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      monitorForm: {
        form: {
          is_standard: null,
          name: "",
          pid: "",
          category_id: [],
        },
        list_xs: [],
        list: [],
      },
      info: [],
      listLoading: false,
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },
      // 监听滚动
      searchBarFixed: false,
      isEdit: false,
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  created() {
    // 列表
    this.opening_getUnOpening();
  },
  beforeRouteLeave(to, from, next) {
    if (this.isEdit) {
      setTimeout(() => {
        this.$confirm(
          "您已经有数据操作，离开页面系统不会保存您的操作，确定离开吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            // 正常跳转
            next();
          })
          .catch(() => {
            next(false);
          });
      }, 200);
    } else {
      next();
    }
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 300
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.opening_getUnOpening();
    },
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.$refs["changeGoodsInput"].name = "";
      this.opening_getUnOpening();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.opening_getUnOpening();
    },
    changePage(page) {
      this.current.page = page;
      this.opening_getUnOpening();
    },
    // 删除
    delet(index) {
      this.isEdit = true;
      this.monitorForm.list.data.push(
        JSON.parse(JSON.stringify(this.monitorForm.list_xs[index]))
      );
      this.monitorForm.list_xs.splice(index, 1);
    },
    // 确认
    confirm(index, row) {
      this.isEdit = true;
      if (
        parseFloat(this.monitorForm.list.data[index].num) >= 0 &&
        parseFloat(this.monitorForm.list.data[index].price) >= 0
      ) {
        let ind = 0;
        if (this.monitorForm.list_xs.length != 0) {
          let title = row.spu_name ? row.spu_name.title : "";
          let name = row.goods.name + "【" + title + "】";
          this.monitorForm.list_xs.map((e) => {
            if (e.id == row.id) {
              ind = e.id;
              return;
            }
          });
          if (ind == 0) {
            this.monitorForm.list_xs.push(
              JSON.parse(JSON.stringify(this.monitorForm.list.data[index]))
            );
            this.monitorForm.list.data.splice(index, 1);
          } else {
            this.$confirm(`${name}商品已存在，确认替换吗？`, {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.monitorForm.list.data.splice(index, 1);
                this.monitorForm.list_xs.forEach((i) => {
                  if (i.id == ind) {
                    i.num = row.num;
                    i.price = row.price;
                  }
                });
                ind = 0;
              })
              .catch(() => {});
          }
        } else {
          this.monitorForm.list_xs.push(
            JSON.parse(JSON.stringify(this.monitorForm.list.data[index]))
          );
          this.monitorForm.list.data.splice(index, 1);
        }
      } else {
        this.$message.error("期初库存，期初进价不能为空，可以为0或者数字");
      }
    },
    // 保存
    preservation() {
      this.$refs["userListFrom"].validate((valid) => {
        if (valid) {
          if (this.monitorForm.list_xs.length == 0) {
            this.$message.error("请至少添加一个商品");
            return;
          }

          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name, { type: 3 })) +
                  apiUrl().appsecret
              ),
            },
            apiUrl().name,
            { list: JSON.stringify(this.order_data()), type: 3 }
          );
          storage_add(data).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: "添加成功",
                type: "success",
              });
              this.isEdit = false;
              this.$router.go(-1);
            } else {
              this.$message.error(res.errmsg);
            }
          });
        }
      });
    },
    order_data() {
      let arry = [];
      let sz = JSON.parse(JSON.stringify(this.monitorForm.list_xs));
      sz.map((e) => {
        arry.push({
          goods_id: e.goods_id,
          goods_spu_id: e.id,
          num: e.num,
          price: e.price,
        });
      });
      return arry;
    },
    // 列表
    opening_getUnOpening() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      opening_getUnOpening(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.options = recursion(res.data.categoryList, true);
          res.data.list.data.map((e) => {
            e.num = "";
            e.price = "";
          });
          this.monitorForm.list = res.data.list;
          this.info = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.monitorForm.form));
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);

      return form;
    },
    // input框聚焦时
    inputFocus(scope, $event) {},
    // 失去焦点
    inputBlur(scope, $event) {},
    nextFocus(scope, $event, type) {
      let index = scope.$index;
      let val = $event.target.value;
      if (/^(\d+\.?)?\d{0,2}$/.test(parseFloat(val)) && val != "") {
        if (type == 1) {
        } else if (type == 2) {
          $event.target.blur();
          this.confirm(scope.$index);
          this.$nextTick(() => {
            let str = "list_data_" + scope.$index + "_num";
            let input = document
              .querySelector(`.${str}`)
              .querySelector("input");
            console.log(input);
            input.focus();
          });
        }
      } else {
        $event.target.value = "";
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.batch-wrap {
  align-items: center;
  margin-top: 10px;
  /deep/.el-form-item--small.el-form-item{
    margin-bottom: 6px;
  }
}
/deep/.el-form--inline .el-form-item {
  margin-right: 0;
}
.mainsu {
  .mainor_form form {
    width: 100%;
  }
  .reset {
    background: none;
    color: #03a98e;
  }
  .main_table {
    /deep/.el-table--small td {
      padding-top: 0;
    }
    /deep/.el-form-item--small.el-form-item {
      margin-bottom: 0;
      margin-top: 12px;
      margin-right: 0;
    }
  }
  .main_table_xs {
    /deep/.el-table--small td {
      padding-top: 12px;
    }
  }
  .main_xq {
    ul {
      li {
        .main_xqi {
          width: 80%;
          margin-left: 5px;
        }
      }
    }
  }
}
</style>
